<template>
  <!--  jiera-->
  <div class="flex gap-3">
    <div class="flex-1">
      <div class="flex flex-col gap-3">
        <div class="bg-white rounded p-3" v-if="typeId !== '5' && typeId !== '7'">
          <div class="mb-2" style="display: flex">
            <el-button
              v-for="item in listToUse"
              :type="item.isActive ? 'primary' : 'default'"
              :key="item.id"
              @click="!item.needLogin ? clickHandle(item) : () => {}"
              v-login="!!item.needLogin ? () => clickHandle(item) : undefined"
              >{{ item.name }}
            </el-button>
            <div style="margin-left: 3%" v-if="typeId === '10'">
              <el-select
                v-model="distance"
                clearable
                placeholder="请选择附近的公里数"
                style="width: 180px"
                @change="getListByDistance"
              >
                <el-option
                  v-for="itemDistance in options"
                  :key="itemDistance.value"
                  :label="itemDistance.label"
                  :value="itemDistance.value"
                />
              </el-select>
            </div>
          </div>
          <div v-show="showOnlyChat">
            <div class="bg-gray-100 p-3.5 my-1 rounded" v-nologin-show>
              点击
              <el-button type="primary" link v-login="() => {}">登录</el-button>
              ,快来和大家讨论吧~
            </div>
            <div class="task_input" v-login-show>
              <MyTextarea v-model="ordinaryPost">
                <el-button type="primary" round @click="handleAddTask" style="padding: 0 30px"
                  >发布
                </el-button>
              </MyTextarea>
            </div>
          </div>
        </div>
        <div class="post_list_container bg-white p-5">
          <ArticleList
            :list="data"
            :pagination="pagination"
            @refresh="handleRefresh"
            :typeId="route.params.id"
          ></ArticleList>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import type { ComputedRef } from 'vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const typeId = computed(() => route.params.id as string)
const activeName = ref(-1)
const userId = computed(() => userStore.userInfo?.uid || '1000000')
const showOnlyChat = ref(false)
const distance = ref()
const data = ref([])
const pagination = ref({
  pageSize: 10,
  pageNum: 1,
  total: 0,
})

const location = localStorage.getItem('location')
  ? JSON.parse(localStorage.getItem('location') as string)
  : {
      longitude: 120.43717074436847,
      latitude: 31.43021261550411,
    }

const ordinaryPost = ref({
  content: '',
  images: [],
})

const value = ref('')
const options = [
  {
    value: '100',
    label: '100km内',
  },
  {
    value: '300',
    label: '300km内',
  },
  {
    value: '500',
    label: '500km内',
  },
  {
    value: '1000',
    label: '1000km内',
  },
  {
    value: '10000',
    label: '大于1000km',
  },
]

// 任务的list
const list = ref<
  { name: string; id: number; isActive?: boolean; path?: string; needLogin?: boolean }[]
>([
  {
    name: '发任务',
    id: -2,
    isActive: true,
    path: '/main/task/handle',
    needLogin: true,
  },
  {
    name: '随便聊',
    id: -1,
    isActive: false,
  },
  {
    name: '找帮忙',
    id: 2,
    path: '/main/typePostList/2',
    isActive: false,
  },
])

// 交流的list
const listCommunicate = ref<
  { name: string; id: number; isActive?: boolean; path?: string; needLogin?: boolean }[]
>([
  {
    name: '随便聊',
    id: -1,
    isActive: true,
  },
])

// 求助的list
const listAsk = ref<
  { name: string; id: number; isActive?: boolean; path?: string; needLogin?: boolean }[]
>([
  {
    name: '发求助',
    id: -2,
    isActive: true,
    path: '/main/task/handle',
    needLogin: true,
  },
  {
    name: '随便聊',
    id: -1,
    isActive: false,
  },
])

// 好友征召的list
const friendList = ref<
  { name: string; id: number; isActive?: boolean; path?: string; needLogin?: boolean }[]
>([
  {
    name: '好友征召',
    id: 10,
    isActive: true,
    path: '/main/task/handle',
    needLogin: true,
  },
])

// 根据typeId的值动态返回要用于v-for循环的列表
const listToUse: ComputedRef<any[]> = computed(() => {
  if (typeId.value === '0') {
    return listCommunicate.value
  }
  if (typeId.value === '1') {
    return list.value
  } else if (typeId.value === '2') {
    return listAsk.value
  } else if (typeId.value === '10') {
    return friendList.value
  }
  return list
})

// 点击按钮判断勾选默认任务类型
const clickHandle = (item: any) => {
  list.value.forEach((item: any) => {
    item.isActive = false
  })
  item.isActive = true
  if (item.name === '随便聊') {
    showOnlyChat.value = true
  } else {
    showOnlyChat.value = false
  }
  if (item.path) {
    router.push({
      path: item.path,
      query: {
        typeId: typeId.value,
      },
    })
  }
}

const getListByDistance = (selectedDistance: string | number) => {
  distance.value = selectedDistance
  getData()
}

const getData = async () => {
  const queryData = {
    type: Number(typeId.value) >= 0 ? typeId.value : undefined,
    x: Number(typeId.value) == 10 ? location.longitude : undefined,
    y: Number(typeId.value) == 10 ? location.latitude : undefined,
    pageSize: pagination.value.pageSize,
    pageNum: pagination.value.pageNum,
    distance: distance.value !== undefined ? distance.value : undefined,
  }
  if (localStorage.getItem('location') == null && Number(typeId.value) < 0) {
    ElMessage({
      message: '坐标获取失败 自动定位服务器所在地 请更换edge浏览器',
      type: 'warning',
    })
  }
  const result = await service.task.list(queryData)
  data.value = result.list
  pagination.value.total = result.total
}

onMounted(async () => {
  // 提示
  if (typeId.value === '0') {
    showOnlyChat.value = true
  }
  getData()
})

watch(typeId, () => {
  if (typeId.value === '0') {
    showOnlyChat.value = true
  } else {
    showOnlyChat.value = false
  }
  pagination.value.pageNum = 1
  getData()
})

const handleRefresh = (pagination2?: any) => {
  if (pagination2) {
    pagination.value.pageSize = pagination2.pageSize
    pagination.value.pageNum = pagination2.pageNum
  }
  getData()
}

// 首页随便聊tab的发布按钮
const handleAddTask = async () => {
  const data = {
    type: 0,
    description: ordinaryPost.value.content,
    images: ordinaryPost.value.images,
    x: location.longitude || 120.58,
    y: location.latitude || 31.29,
  }
  if (data.description.trim() !== '') {
    await service.task.add(data)
    getData()
    // 清空images
    ordinaryPost.value.images = []
    ordinaryPost.value.content = ''
  } else {
    ElMessage.warning('输入内容不为空~')
  }
}
</script>
